﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interface.Api;
using System.Net;
using System.Xml;
using System.IO;

namespace Fanfou.Api
{
	public class MyTL : IApi
	{
		virtual public ApiResults execute(ApiArgs Args)
		{
			HttpWebRequest request = null;
			HttpWebResponse response = null;

			if (Args.GetType() != typeof(TLArgs))
			{
				throw new Exception("MyTL.execute(): Expecting arguments of type TLArgs but got " + Args.GetType().ToString());
			}
			TLArgs args = (TLArgs)Args;

			if (args.username.Length == 0)
			{
				throw new Exception("MyTL.execute(): username must not be empty.");
			}

			// Sending request
			request = (HttpWebRequest)WebRequest.Create(URL.MyTL + "?id=" + args.username);
			request.ContentType = "application/x-www-form-urlencoded";
			request.Method = "GET";
			request.Headers.Add("Authorization", "Basic " + Args.authorization);
			request.Timeout = 10000;

			try
			{
				response = (HttpWebResponse)request.GetResponse();
			}
			catch (WebException ex)
			{
				response = (HttpWebResponse)ex.Response;
			}
			finally
			{
			}

			TLResults results = buildResults(response);
			if (response != null)
			{
				response.Close();
			}
			return results;
		}

		protected TLResults buildResults(HttpWebResponse response)
		{
			TLResults results = new TLResults();

			if (response != null)
			{
				results.status = response.StatusCode;

				Stream stream = response.GetResponseStream();
				XmlDocument xml = new XmlDocument();
				xml.Load(stream);
				stream.Close();

				results.posts = parseXml(xml);
			}
			else
			{
				results.status = HttpStatusCode.RequestTimeout;
			}
			return results;
		}

		protected Post[] parseXml(XmlDocument Xml)
		{
			Post[] posts;
			try
			{
				posts = new Post[Xml.DocumentElement.ChildNodes.Count];
				for (int i = 0; i < Xml.DocumentElement.ChildNodes.Count; ++i)
				{
					posts[i] = new Post();

					XmlNode status = Xml.DocumentElement.ChildNodes[i];

					posts[i].id			= status.SelectSingleNode("id").InnerText;
					posts[i].message	= status.SelectSingleNode("text").InnerText;
					posts[i].dateTime		= toDateTime(status.SelectSingleNode("created_at").InnerText);

					XmlNode user = status.SelectSingleNode("user");

					posts[i].userId		= user.SelectSingleNode("id").InnerText;
					posts[i].name		= user.SelectSingleNode("name").InnerText;
				}
			}
			catch (System.Exception)
			{
				posts = null;
			}

			return posts;
		}

		private DateTime toDateTime(string str)
		{
			string[] temp = str.Split(' ');

			int month = -1;
			switch (temp[1])
			{
			case "Jan":
				month = 1;
				break;
			case "Feb":
				month = 2;
				break;
			case "Mar":
				month = 3;
				break;
			case "Apr":
				month = 4;
				break;
			case "May":
				month = 5;
				break;
			case "June":
				month = 6;
				break;
			case "Jun":
				month = 6;
				break;
			case "Jul":
				month = 7;
				break;
			case "July":
				month = 7;
				break;
			case "Aug":
				month = 8;
				break;
			case "Sep":
				month = 9;
				break;
			case "Sept":
				month = 9;
				break;
			case "Oct":
				month = 10;
				break;
			case "Nov":
				month = 11;
				break;
			case "Dec":
				month = 12;
				break;
			}

			int day = Int32.Parse(temp[2]);
			int year = Int32.Parse(temp[5]);

			string[] timeStr = temp[3].Split(':');
			int hour = Int32.Parse(timeStr[0]);
			int minu = Int32.Parse(timeStr[1]);
			int sec = Int32.Parse(timeStr[2]);

			DateTime dt = new DateTime(year, month, day, hour, minu, sec, DateTimeKind.Utc);
			return dt.ToLocalTime();
		}
	}
}
